var container = null;

function initChart(divId) {

    //"chartdiv"
    container = am4core.create(divId, am4core.Container);
    container.width = am4core.percent(100);
    container.height = am4core.percent(100);
    // container.width = 1900; // 宽度为 800 像素
    // container.height = 600; // 高度为 600 像素

    var interfaceColors = new am4core.InterfaceColorSet();

    var chart = container.createChild(am4plugins_timeline.CurveChart);
    chart.curveContainer.padding(5, 0, 0, 0);

    chart.dateFormatter.dateFormat = "yyyy-MM-dd hh:mm";
    chart.dateFormatter.inputDateFormat = "yyyy-MM-dd hh:mm";
    chart.fontSize = 18;
    chart.tooltipContainer.fontSize = 12;
    chart.maskBullets = false;

    //向表格Y轴增加标签
    var categoryAxis = chart.yAxes.push(new am4charts.CategoryAxis());
    categoryAxis.dataFields.category = "category";
    categoryAxis.renderer.grid.template.disabled = false;
    categoryAxis.renderer.grid.template.strokeWidth = 1;
    //          categoryAxis.renderer.grid.template.strokeOpacity = 0.7;
    categoryAxis.renderer.labels.template.paddingRight = 30; //Y轴标签与坐标轴的间距
    categoryAxis.renderer.minGridDistance = 10;
    categoryAxis.renderer.innerRadius = 0;
    categoryAxis.renderer.radius = 400;
    categoryAxis.renderer.grid.template.location = 1;


    //向表格中X轴增加时间轴
    var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
    dateAxis.dateFormatter.utc = true;
    dateAxis.renderer.minGridDistance = 100; //时间轴时间标签的间距为100像素


    // const oneDaysBefore = getDateBeforeDays(1);
    // const oneDayAfter = getDateAfterDays(1);
    // const oneDaysBeforeStr = formatDate(oneDaysBefore);
    // const oneDayAfterStr = formatDate(oneDayAfter);
    // dateAxis.min = new Date(oneDaysBeforeStr).getTime();
    // dateAxis.max = new Date(oneDayAfterStr).getTime();

    dateAxis.baseInterval = { count: 1, timeUnit: "minute" };
    // 设置baseInterval为“小时”
    // dateAxis.baseInterval = { count: 1, timeUnit: "hour" }; // 时间间隔为1小时
    // dateAxis.renderer.minGridDistance = 60; // 时间轴时间标签的最小间距

    // 强制显示以天和小时为主的网格标签
    dateAxis.groupData = false; // 禁止自动分组以确保显示细粒度数据
    dateAxis.dateFormats.setKey("hour", "MM-ddTHH:mm"); // 小时显示格式
    dateAxis.dateFormats.setKey("day", "MM-dd"); // 天显示格式
    // dateAxis.periodChangeDateFormats.setKey("day", "yyyy-MM-dd"); // 天切换格式
    dateAxis.periodChangeDateFormats.setKey("hour", "HH"); // 小时切换格式

    dateAxis.startLocation = -0.5;
    dateAxis.renderer.autoScale = false;
    dateAxis.renderer.polyspline.tensionX = 0.8;
    dateAxis.renderer.tooltipLocation = 0;
    dateAxis.renderer.grid.template.disabled = true;
    dateAxis.renderer.line.strokeDasharray = "1,4";
    dateAxis.renderer.line.strokeOpacity = 0.7;
    dateAxis.tooltip.background.fillOpacity = 0.2;
    dateAxis.tooltip.background.cornerRadius = 5;
    dateAxis.tooltip.label.fill = new am4core.InterfaceColorSet().getFor("alternativeBackground");
    dateAxis.tooltip.label.paddingTop = 7;
    // 设置tooltip的日期和时间格式
    dateAxis.tooltipDateFormat = "yyyy-MM-dd HH:mm:ss";

    //设置时间轴的样式
    var labelTemplate = dateAxis.renderer.labels.template;
    labelTemplate.verticalCenter = "middle";
    labelTemplate.fillOpacity = 0.7;
    labelTemplate.fontSize = 12;
    labelTemplate.background.fill = interfaceColors.getFor("background");
    labelTemplate.background.fillOpacity = 1;
    labelTemplate.padding(7, 7, 7, 7); //时间轴上时间标签的边距


    //X轴时间标签跟着鼠标移动
    var cursor = new am4plugins_timeline.CurveCursor();
    chart.cursor = cursor;
    cursor.xAxis = dateAxis;
    cursor.yAxis = categoryAxis;
    cursor.lineY.disabled = true;
    cursor.lineX.strokeDasharray = "1,4";
    cursor.lineX.strokeOpacity = 1;

    //顶部滚动条
    chart.scrollbarX = new am4core.Scrollbar();
    chart.scrollbarX.align = "center"
    chart.scrollbarX.width = am4core.percent(75);
    // chart.scrollbarX.start = 0.10; // Set the start position to 25%
    // chart.scrollbarX.end = 0.60;   // Set the end position to 75%


    // 在滑动条下方添加文本标签
    var timeLabel = chart.createChild(am4core.Label);
    timeLabel.text = "";
    timeLabel.isMeasured = false;
    timeLabel.x = am4core.percent(50);
    timeLabel.horizontalCenter = "middle";
    timeLabel.y = chart.scrollbarX.pixelY + 30; // 滑动条下方偏移


    // 监听滑动条的范围变化
    chart.scrollbarX.events.on("rangechanged", function () {
        var startDate = chart.xAxes.getIndex(0).positionToDate(chart.scrollbarX.start);
        var endDate = chart.xAxes.getIndex(0).positionToDate(chart.scrollbarX.end);

        // 格式化显示时间（根据需求自定义格式）
        var dateFormatter = chart.dateFormatter;
        dateFormatter.dateFormat = "yyyy-MM-ddTHH:mm:ss";

        timeLabel.text = dateFormatter.format(startDate) + " To " + dateFormatter.format(endDate);
    });

    dateAxis.renderer.tooltipLocation2 = 0;
    categoryAxis.cursorTooltipEnabled = false;

    // 获取当前 UTC 时间
    var nowUTC = new Date();

    // 在 X 轴上添加 Guide（竖线）
    var range = dateAxis.axisRanges.create();
    range.date = nowUTC;
    range.grid.stroke = am4core.color("red"); // 线条颜色
    range.grid.strokeWidth = 2; // 线条宽度
    range.grid.strokeOpacity = 1; // 透明度

    // 添加 Tooltip 显示时间
    // range.label.text = "Now (UTC)";
    // range.label.rotation = 90;
    // range.label.horizontalCenter = "right";
    // range.label.verticalCenter = "middle";
    // range.label.dy = -10;

    return chart
}

function getRandomMinutes(start, end) {
    return Math.floor(Math.random() * (end - start + 1)) + start;
}

function formatTime(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}`;
}

function getRandomTimesWithInterval() {
    const now = new Date();
    const startMinutes = now.getMinutes() + now.getHours() * 60;

    // Calculate the minutes for the first time
    const firstTimeMinutes = startMinutes + getRandomMinutes(0, (24 * 60) - startMinutes - 60); // Ensure there's enough room for the interval

    // Calculate the interval in minutes (between 30 and 60 minutes)
    const intervalMinutes = getRandomMinutes(30, 60);

    // Calculate the minutes for the second time
    const secondTimeMinutes = firstTimeMinutes + intervalMinutes;

    // Create Date objects for the first and second times
    const firstTime = new Date(now.setMinutes(firstTimeMinutes % (24 * 60)));
    const secondTime = new Date(now.setMinutes(secondTimeMinutes % (24 * 60)));

    // Ensure the second time is on the same day as the first time (in case the interval wraps around midnight)
    secondTime.setDate(now.getDate());

    // Format and return the times
    return [formatTime(firstTime), formatTime(secondTime)];
}

function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
}

function getCurrentDate() {
    const now = new Date();
    return now;
}

function getDateBeforeDays(days) {
    const now = getCurrentDate();
    const newDate = new Date(now);
    newDate.setDate(now.getDate() - days);
    return newDate;
}

function getDateAfterDays(days) {
    const now = getCurrentDate();
    const newDate = new Date(now);
    newDate.setDate(now.getDate() + days);
    return newDate;
}

function randonData() {

    var colorSet = new am4core.ColorSet();
    colorSet.saturation = 0.5;

    var tdata = [{
        "category": "GRM",
        "start": "2019-11-10 03:00",
        "end": "2019-11-10 03:10",
        "disabled1": false,
        "color": colorSet.getIndex(0),
        "task": "GRM 001"
    }, {
        "category": "Eclars",
        "start": "2019-11-10 10:00",
        "end": "2019-11-10 17:00",
        "disabled2": false,
        "color": colorSet.getIndex(3),
        "task": "Eclars 2024"
    }, {
        "category": "GSP",
        "start": "2019-11-10 06:00",
        "end": "2019-11-10 11:00",
        "task": "GSP 001",
        "color": colorSet.getIndex(5),
        "bulletf1": true
    }, {
        "category": "ES",
        "start": "2019-11-10 11:30",
        "end": "2019-11-10 16:30",
        "color": colorSet.getIndex(7),
        "task": "ES"
    }, {
        "category": "SAA",
        "start": "2019-11-10 16:00",
        "end": "2019-11-10 18:00",
        "color": colorSet.getIndex(9),
        "task": "SAA"
    }];

    $.each(tdata, function (index, element) {
        const [time1, time2] = getRandomTimesWithInterval();
        element['start'] = time1;
        element['end'] = time2;
    })

    return tdata;
}

function showFlagExample(){
    //需要取消对categoryList.push("")的注释
    var eventSeries = chart.series.push(new am4plugins_timeline.CurveLineSeries());
    eventSeries.dataFields.dateX = "eventDate";
    eventSeries.dataFields.categoryY = "category";
    eventSeries.data = [
        { category: "", eventDate: "2025-01-15 03:00", letter: "GRB250116A", description: "Something happened here" },
        { category: "", eventDate: "2025-01-16 03:00", letter: "B", description: "Something happened here" },
        { category: "", eventDate: "2025-01-17 03:00", letter: "C", description: "Something happened here" }
    ];
    eventSeries.strokeOpacity = 0;

    var flagBullet = eventSeries.bullets.push(new am4plugins_bullets.FlagBullet())
    flagBullet.label.propertyFields.text = "letter";
    flagBullet.label.fontSize = 10;
    flagBullet.locationX = 0;
    flagBullet.tooltipText = "{description}";
    flagBullet.events.on("hit", clickBullet);
}


function requestUrl(rootUrl, beginTimeParmName="begTime") {


    const currentDate = getCurrentDate();
    const twoDaysBefore = getDateBeforeDays(2);
    const oneDayAfter = getDateAfterDays(2);

    const twoDaysBeforeStr = formatDate(twoDaysBefore);
    const oneDayAfterStr = formatDate(oneDayAfter);
    
    // console.log('前两天日期:', twoDaysBeforeStr);
    // console.log('后一天日期:', oneDayAfterStr);

    url = rootUrl + "?"+beginTimeParmName+"="+twoDaysBeforeStr+"&endTime="+oneDayAfterStr
    console.log(url)
    // url = "/data/getDurObs.json"

    dataList = []
    $.ajax({
        url: url, 
        type: 'GET', 
        dataType: 'json', // 返回的数据类型
        async: false, // 设置为同步请求
        success: function (data) {
            if(data['errorCode']==0 || data['errCode']==0){
                dataList = data.data;
            }
        },
        error: function (xhr, status, error) {
            console.error('请求失败:', status, error); // 输出错误信息
        }
        });
    return dataList;
}

function getTrigger() {

    url = "https://www.svom.cn//alertCenter/alertApi/getFmtdTriggers"
    dataList = requestUrl(url, 'beginTime')
    // console.log(dataList)
    
    tdata = []
    $.each(dataList, function (index, element) {
        // console.log(element)
        const tcategory = element['cls'].toUpperCase();
        let startDateStr = element['beginTime']+"Z";
        let endDateStr = element['endTime']+"Z";
        startDate = new Date(startDateStr);
        endDate = new Date(endDateStr);
        
        const info = element["info"];
        const triggerName = info["triggerName"];
        
        tdata.push({
            'category': tcategory,
            'eventDate': startDate,
            "start": startDate,
            "end": endDate,
            "color": "red",
            'letter': triggerName,
            'startEndTime': startDateStr.substring(0, 19),
            'description': "triggerName: "+triggerName+", startDate: "+startDateStr.substring(0, 19)
        })
    });

    return tdata
}

function getES() {

    url = "https://www.svom.cn/alertCenter/workFileApi/getFmtdEss"
    dataList = requestUrl(url, 'beginTime')
    // console.log(dataList)
    
    tdata = []
    $.each(dataList, function (index, element) {
        // console.log(element)
        const tcategory = element['cls'].toUpperCase();
        let startDateStr = element['beginTime']+"Z";
        let endDateStr = element['endTime']+"Z";
        startDate = new Date(startDateStr);
        endDate = new Date(endDateStr);
        const info = element["info"];
        const fileId = info["fileId"];
        
        tdata.push({
            'category': tcategory,
            'eventDate': startDate,
            "start": startDate,
            "end": endDate,
            "color": "red",
            'letter': "fileId: "+fileId,
            'startEndTime': startDateStr.substring(0, 19)+" ; "+endDateStr.substring(0, 19),
            'description': "startDate: "+startDateStr.substring(0, 19)+", endDate: "+endDateStr.substring(0, 19)
        })
    })

    return tdata
}


function getWrokplan_old() {

    // url = "https://www.svom.cn/svomGP/obs-corr-info/getDurObs"
    url = "https://www.svom.cn/svomGP/obs-corr-info/getDurObsPlans"
    dataList = requestUrl(url)

    tdata = []
    $.each(dataList, function (index, element) {
        const planId = element['planId'];
        const workplanType = element['workplanType'];
        const obsType = element['obsType'];
        const startDate = element['startDate'];
        const endDate = element['endDate'];
        tdata.push({
            "category": workplanType,
            "start": startDate,
            "end": endDate,
            "color": "red",
            "task": "workplan Id: "+planId+", obsType: "+obsType
        })
    })

    return tdata
}


function getWrokplan() {

    url = "https://www.svom.cn/svomGP/obs-corr-info/getFmtdDurObsPlans"
    dataList = requestUrl(url, 'beginTime')
    // console.log(dataList)
    
    tdata = []
    $.each(dataList, function (index, element) {
        // console.log(element)
        let tcategory = element['cls'];
        let startDateStr = element['beginTime']+"Z";
        let endDateStr = element['endTime']+"Z";
        startDate = new Date(startDateStr);
        endDate = new Date(endDateStr);
        const info = element["info"];
        const gspId = info["gspId"];
        const sourceId = info["sourceId"];

        if(sourceId != null && sourceId.length > 0){
            tdescription = "sourceId: "+sourceId+", startDate: "+startDateStr.substring(0, 19)+", endDate: "+endDateStr.substring(0, 19)
        }else{
            tdescription = "startDate: "+startDateStr.substring(0, 19)+", endDate: "+endDateStr.substring(0, 19)
        }

        tcategory = tcategory.replace("-work-plan", "")
        tcategory = tcategory.toUpperCase();
        
        tdata.push({
            'category': tcategory,
            'eventDate': startDate,
            "start": startDate,
            "end": endDate,
            "color": "red",
            'letter': "gspId: "+gspId,
            'startEndTime': startDateStr.substring(0, 19)+" ; "+endDateStr.substring(0, 19),
            'description': tdescription
        })
    })

    return tdata
}

function getGSP() {

    url = "https://www.svom.cn/alertCenter/workFileApi/getFmtdGsps"
    dataList = requestUrl(url, 'beginTime')
    // console.log(dataList)
    
    tdata = []
    $.each(dataList, function (index, element) {
        // console.log(element)
        const tcategory = element['cls'].toUpperCase();
        let startDateStr = element['beginTime']+"Z";
        let endDateStr = element['endTime']+"Z";
        startDate = new Date(startDateStr);
        endDate = new Date(endDateStr);
        const info = element["info"];
        const gspId = info["gspId"];
        
        tdata.push({
            'category': tcategory,
            'eventDate': startDate,
            "start": startDate,
            "end": endDate,
            "color": "red",
            'letter': "gspId: "+gspId,
            'startEndTime': element['beginTime'].substring(0, 19),
            'description': element['beginTime'].substring(0, 19)
        })
    })

    return tdata
}

function getVTSAA() {

    url = "https://www.svom.cn/alertCenter/workFileApi/getFmtdVtSaas"
    dataList = requestUrl(url, 'beginTime')
    // console.log(dataList)
    
    tdata = []
    $.each(dataList, function (index, element) {
        // console.log(element)
        const tcategory = element['cls'].toUpperCase();
        let startDateStr = element['beginTime']+"Z";
        let endDateStr = element['endTime']+"Z";
        startDate = new Date(startDateStr);
        endDate = new Date(endDateStr);
        const info = element["info"];
        const gspId = info["gspId"];
        
        tdata.push({
            'category': tcategory,
            'eventDate': startDate,
            "start": startDate,
            "end": endDate,
            "color": "red",
            'letter': "gspId: "+gspId,
            'startEndTime': startDateStr.substring(0, 19)+" ; "+endDateStr.substring(0, 19),
            'description': "startDate: "+startDateStr.substring(0, 19)+", endDate: "+endDateStr.substring(0, 19)
        })
    })

    return tdata
}

function getSBandPlan() {

    url = "https://www.svom.cn/alertCenter/workFileApi/getFmtdSplans"
    dataList = requestUrl(url, 'beginTime')
    // console.log(dataList)
    
    tdata = []
    $.each(dataList, function (index, element) {
        // console.log(element)
        const tcategory = element['cls'].toUpperCase();
        let startDateStr = element['beginTime']+"Z";
        let endDateStr = element['endTime']+"Z";
        startDate = new Date(startDateStr);
        endDate = new Date(endDateStr);
        const info = element["info"];
        const gspId = info["gspId"];
        const orbitCircle = info["orbitCircle"];
        const facilityId = info["facilityId"];
        
        tdata.push({
            'category': "SBandPlan",
            'eventDate': startDate,
            "start": startDate,
            "end": endDate,
            "color": "red",
            'letter': "gspId: "+gspId,
            'startEndTime': startDateStr.substring(0, 19)+" ; "+endDateStr.substring(0, 19),
            'description': "startDate: "+startDateStr.substring(0, 19)
                +", endDate: "+endDateStr.substring(0, 19)
                +", orbitCircle: "+orbitCircle
                +", facilityId: "+facilityId
        })
    })
    // console.log(tdata)

    return tdata
}

function getXBandPlan() {

    url = "https://www.svom.cn/alertCenter/workFileApi/getFmtdXplans"
    dataList = requestUrl(url, 'beginTime')
    // console.log(dataList)
    
    tdata = []
    $.each(dataList, function (index, element) {
        // console.log(element)
        const tcategory = element['cls'].toUpperCase();
        let startDateStr = element['beginTime']+"Z";
        let endDateStr = element['endTime']+"Z";
        startDate = new Date(startDateStr);
        endDate = new Date(endDateStr);
        const info = element["info"];
        const gspId = info["gspId"];
        const orbitCircle = info["orbitId"];
        
        tdata.push({
            'category': "XBandPlan",
            'eventDate': startDate,
            "start": startDate,
            "end": endDate,
            "color": "red",
            'letter': "gspId: "+gspId,
            'startEndTime': startDateStr.substring(0, 19)+" ; "+endDateStr.substring(0, 19),
            'description': "startDate: "+startDateStr.substring(0, 19)+", endDate: "+endDateStr.substring(0, 19)
            +", orbitCircle: "+orbitCircle
        })
    })

    return tdata
}

function showLine(showData, showCircle=false){

    //绘制内容
    var series = chart.series.push(new am4plugins_timeline.CurveColumnSeries());
    series.columns.template.height = am4core.percent(50);
    // series.columns.template.tooltipText = "{task}, [bold]{openDateX}[/] - [bold]{dateX}[/]";
    // series.columns.template.tooltipText = "[bold]{openDateX}[/] - [bold]{dateX}[/]";
    series.columns.template.tooltipText = "{description}";
    series.data = showData;

    series.dataFields.openDateX = "start";
    series.dataFields.dateX = "end";
    series.dataFields.categoryY = "category";
    series.columns.template.propertyFields.fill = "color"; // get color from data
    series.columns.template.propertyFields.stroke = "color";
    series.columns.template.strokeOpacity = 0;

    series.columns.template.adapter.add("fill", function (fill, target) {
        categoryY = target.dataItem.categories['categoryY']
        // console.log(categoryY);
        if(categoryY=="XBandPlan" || categoryY=="SBandPlan"){
            tcolor = am4core.color("#FF0000");
        }else{
            tcolor = chart.colors.getIndex(target.dataItem.index * 3);
        }
        return tcolor;
    });
    series.columns.template.events.on("hit", clickBullet);

    if(showCircle){
        var circleBullet = series.bullets.push(new am4charts.CircleBullet());
        circleBullet.circle.radius = 1;
        circleBullet.circle.strokeOpacity = 0;
        circleBullet.propertyFields.fill = "color";
        circleBullet.locationX = 0;
        circleBullet.tooltipText = "{description}";
        // circleBullet.events.on("hit", clickBullet);
    }
}

function showCircle(showData, circleRadius=3){

    var eventSeries = chart.series.push(new am4plugins_timeline.CurveLineSeries());
    eventSeries.dataFields.dateX = "eventDate";
    eventSeries.dataFields.categoryY = "category";
    eventSeries.data = showData;
    eventSeries.strokeOpacity = 0;

    var circleBullet = eventSeries.bullets.push(new am4charts.CircleBullet());
    circleBullet.circle.radius = circleRadius;
    circleBullet.circle.strokeOpacity = 0;
    circleBullet.propertyFields.fill = "color";
    circleBullet.locationX = 0;
    circleBullet.tooltipText = "{description}";
    circleBullet.events.on("hit", clickBullet);

}

function showRectangle(showData, circleRadius=3){

    var eventSeries = chart.series.push(new am4plugins_timeline.CurveLineSeries());
    eventSeries.dataFields.dateX = "eventDate";
    eventSeries.dataFields.categoryY = "category";
    eventSeries.data = showData;
    eventSeries.strokeOpacity = 0;

    var rectangleBullet = eventSeries.bullets.push(new am4charts.Bullet());
    var rectangle = rectangleBullet.createChild(am4core.Rectangle);
    rectangle.width = 1; // 设置矩形宽度
    rectangle.height = 10; // 设置矩形高度
    rectangle.strokeOpacity = 0;
    rectangle.fill = am4core.color("#000000");
    rectangleBullet.locationX = 0;
    rectangleBullet.tooltipText = "{description}";
    rectangleBullet.events.on("hit", clickBullet);

    var rectangleBullet2 = eventSeries.bullets.push(new am4charts.Bullet());
    var rectangle2 = rectangleBullet2.createChild(am4core.Rectangle);
    rectangle2.width = 1; // 设置矩形宽度
    rectangle2.height = 10; // 设置矩形高度
    rectangle2.strokeOpacity = 0;
    rectangle2.fill = am4core.color("#00FF00");
    rectangleBullet2.locationX = 0;
    rectangleBullet2.tooltipText = "{description}";
    rectangleBullet2.events.on("hit", clickBullet);

}

function showFlag(showData, showText=false){

    var eventSeries = chart.series.push(new am4plugins_timeline.CurveLineSeries());
    eventSeries.dataFields.dateX = "eventDate";
    eventSeries.dataFields.categoryY = "category";
    eventSeries.data = showData;
    eventSeries.strokeOpacity = 0;

    var flagBullet = eventSeries.bullets.push(new am4plugins_bullets.FlagBullet())
    if(showText){
        flagBullet.label.propertyFields.text = "letter";
        flagBullet.label.fontSize = 6;
    }
    flagBullet.locationX = 0;
    flagBullet.tooltipText = "{description}";

    // flagBullet.events.on("hit", function(ev) {
    //     var dataItem = ev.target.dataItem;
    //     console.log(dataItem)
    //     if (dataItem) {
    //         document.getElementById("tooltipTextShow").value = dataItem._dataContext.description;
    //     }
    // });
    flagBullet.events.on("hit", clickBullet);
}

function clickBullet(ev) {
    var dataItem = ev.target.dataItem;
    console.log(dataItem)
    if (dataItem) {
        //startEndTime description
        document.getElementById("tooltipTextShow").value = dataItem._dataContext.startEndTime;
    }
}

function drawAllData(){

    /**获取数据 */
    gspList = getGSP();
    workplanList = getWrokplan();
    essList = getES();
    triggerList = getTrigger();
    vtSAAList = getVTSAA();
    sBandPlan = getSBandPlan();
    xBandPlan = getXBandPlan();
    // console.log(vtSAAList);

    // Themes begin
    am4core.useTheme(am4themes_animated);
    // Themes end

    chart = initChart("chartdiv")

    /**Y轴属性排序 */
    categoryList = []
    // categoryList.push("")

    for (let item of triggerList) {
        if(!categoryList.includes(item["category"])){
            categoryList.push(item["category"])
        }
    }
    categoryList.push("GSP")
    categoryList.push("ES")
    categoryList.push("SAA")
    categoryList.push("SBandPlan")
    categoryList.push("XBandPlan")
    // console.log(workplanList)
    for (let item of workplanList) {
        if(!categoryList.includes(item["category"])){
            categoryList.push(item["category"])
        }
    }
    categoryList.push(" ")
    
    allDatas = []
    for (let item of categoryList) {
        allDatas.push({
            "category": item
        })
    }
    // console.log(allDatas)

    allDatas.reverse();
    chart.data = allDatas;
    /**Y轴属性排序 */

    showCircle(gspList);
    showFlag(triggerList,showText=false);

    lineData = [];
    Array.prototype.push.apply(lineData, workplanList);
    Array.prototype.push.apply(lineData, essList);
    Array.prototype.push.apply(lineData, vtSAAList);
    Array.prototype.push.apply(lineData, sBandPlan);
    Array.prototype.push.apply(lineData, xBandPlan);
    showLine(lineData);
    
    // showRectangle(xBandPlan, circleRadius=1);

    showCircle(triggerList, circleRadius=1);
    showCircle(essList, circleRadius=1);
    showCircle(vtSAAList, circleRadius=1);
    showCircle(sBandPlan, circleRadius=1);
    showCircle(xBandPlan, circleRadius=1);

    // showFlagExample(); //需要取消对categoryList.push("")的注释
}

am4core.ready(function () {

    drawAllData();

    // 设置定时器，每30秒刷新一次容器内容
    setInterval(function() {
        // 清空现有内容
        container.dispose();
        drawAllData();
        // 在这里添加新的内容到容器中
        // 例如：添加图表、标题等
    }, 1000*60*30); // 30秒 = 30000毫秒
    

}); // end am4core.ready()